package com.nwpu.coursesupport.realm;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.nwpu.coursesupport.entity.Teacher;
import com.nwpu.coursesupport.entity.bean.Setting;
import com.nwpu.coursesupport.mapper.TeacherMapper;

public class TeacherAuthorizingRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(StudentAuthorizingRealm.class);
	@Autowired
	private TeacherMapper teacherMapper;
	@Autowired
	private Setting setting;
	
	/**
	 * 提供用户信息返回权限信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Collection list=principals.fromRealm(this.getName());
		if(list==null||list.size()<=0){
			return null;
		}
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		//将权限名车个给与info
        simpleAuthorInfo.addRole("teacher"); 
        return simpleAuthorInfo;
	}

	/**
	 * 提供账户信息返回认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		try{
			CustomizedToken token = (CustomizedToken)authcToken; 
			logger.debug(token.getUsername()+"登录");
			Teacher teacher= teacherMapper.findByTeacherCode(token.getUsername());  
	        if(teacher == null){
	        	return null;
	        }
	        token.setId(teacher.getId());
	        token.setName(teacher.getName());
	        token.setImage(teacher.getPicture());
	        ByteSource credentialsSalt = ByteSource.Util.bytes(teacher.getTeacherCode());
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(teacher.getTeacherCode(),teacher.getPassword(),credentialsSalt, this.getName());
	        return authcInfo; 
		}catch(Exception e){
			//e.printStackTrace();
			logger.error("教师登录出现问题："+e.getMessage());
		}
		 return null;
	}

}
